package com.weimob.xh.controller.workhf;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
@RequestMapping("zip/demo")
public class ZipController {

    @PostMapping("/generateZip")
    public ResponseEntity<byte[]> generateZip(@RequestParam("file") MultipartFile file) {
        try {
            // 创建临时文件夹
            File tempDir = Files.createTempDirectory("tempDir").toFile();
            // 解压文件
            File uploadedFile = new File(tempDir, file.getOriginalFilename());
            file.transferTo(uploadedFile);
            // 创建 ZIP 文件
            String zipFilePath = tempDir.getAbsolutePath() + File.separator + "output.zip";
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath));
            // 将文件夹及文件写入 ZIP 文件
            addToZipFile(tempDir.getAbsolutePath(), "", zipOutputStream);
            zipOutputStream.close();
            // 读取 ZIP 文件并返回
            Path zipPath = Paths.get(zipFilePath);
            byte[] zipBytes = Files.readAllBytes(zipPath);
            // 删除临时文件夹
            deleteDirectory(tempDir);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "output.zip");
            return new ResponseEntity<>(zipBytes, headers, HttpStatus.OK);

//            return ResponseEntity.ok()
//                    .header("Content-Disposition", "attachment; filename=output.zip")
//                    .body(zipBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    private void addToZipFile(String directoryPath, String parentDirectory, ZipOutputStream zipOutputStream) throws IOException {
        File directory = new File(directoryPath);
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    String subDirectoryPath = parentDirectory + file.getName() + File.separator;
                    addToZipFile(file.getAbsolutePath(), subDirectoryPath, zipOutputStream);
                } else {
                    byte[] buffer = new byte[1024];
                    FileInputStream inputStream = new FileInputStream(file);
                    zipOutputStream.putNextEntry(new ZipEntry(parentDirectory + file.getName()));
                    int length;
                    while ((length = inputStream.read(buffer)) > 0) {
                        zipOutputStream.write(buffer, 0, length);
                    }
                    inputStream.close();
                }
            }
        }
    }

    private void deleteDirectory(File directory) {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteDirectory(file);
                }
            }
        }
        directory.delete();
    }
}